<template>
	<l-page class="page-card" :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<template slot="options">
			<el-button type="primary" icon="el-icon-plus" class="mt-[32px]" @click="handleAdd">新增 </el-button>
		</template>

		<el-table ref="table" :data="categoryList" :loading="loading" :tree-props="{ children: 'child', hasChildren: 'hasChildren' }" row-key="id" stripe>
			<el-table-column align="center" label="序号" type="index" width="100">
				<template slot-scope="scope">
					<div :class="{ 'pad-left': scope.row.level !== 'L1' }">
						{{ toSort(scope.row) }}
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="分类名称" min-width="156" prop="name" />
			<el-table-column :formatter="emptyToString" align="center" label="分类图标" prop="iconUrl" min-width="156">
				<template slot-scope="scope">
					<img :src="scope.row.iconUrl" width="48" />
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="级别" prop="level" min-width="156">
				<template slot-scope="scope">
					<el-tag :type="scope.row.level === 'L1' ? 'primary' : 'warning'">
						{{ scope.row.level === 'L1' ? '一级分类' : '二级分类' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="展示顺序" min-width="156" prop="sortOrder" sortable>
				<template slot-scope="scope">
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-top" size="mini" type="primary" @click="reSortOrderReduce(scope.row.id, scope.row.pid)"></el-button>
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-bottom" size="mini" type="primary" @click="reSortOrderPlus(scope.row.id, scope.row.pid)"></el-button>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="状态" prop="status" min-width="156">
				<template slot-scope="scope">
					<el-switch v-model.trim.trim="scope.row.status" active-text="上架" class="switch" inactive-text="下架" @change="handleStatusChange(scope.row)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="创建时间" min-width="200" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
						<span>{{ dayjs(scope.row.createTime).format('HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :width="tableAction" align="right" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
						<el-button type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
						<el-button type="danger" @click="handleDelete(scope.row)">删除 </el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<l-dialog v-model="open" :loading.sync="formLoading" :title="title" width="453px" @close="cancel" @formClose="cancel" @formSubmit="submitForm">
			<el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="100px">
				<el-form-item label="分类级别:" prop="level">
					<el-select v-model="form.level" :disabled="form.level == 'L2'" placeholder="请选择分类级别" @change="onLevelChange">
						<el-option label="一级分类" value="L1" />
						<el-option label="二级分类" value="L2" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="form.level === 'L2'" label="父级分类:" prop="pid">
					<el-select v-model="form.pid" placeholder="请选择父级分类">
						<el-option v-for="item in catL1" :key="item.id" :disabled="form.id != null" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="分类名称:" prop="name">
					<el-input v-model.trim="form.name" placeholder="请输入类目名称" maxlength="10" show-word-limit />
				</el-form-item>
				<el-form-item label="分类图标:" prop="iconUrl">
					<l-upload-image v-model="form.iconUrl" height="160px" width="160px" :limit="1" class="w-full">
						<div class="flex flex-col items-center">
							<svg-icon icon-class="add" size="29px" color="#CCCCCC" class="mb-[6px]"></svg-icon>
							<el-tooltip effect="dark" content="支持图片类型jpj,png，图片大小不超过4M。" placement="top">
								<div class="text-[14px] text-[#cccccc] cursor-pointer">上传图片 <i class="el-icon-question"></i></div>
							</el-tooltip>
						</div>
					</l-upload-image>
				</el-form-item>
			</el-form>
		</l-dialog>
	</l-page>
</template>

<script>
import { addCategory, delCategory, exportCategory, getCategory, listCategory, listChild, listParent, sortOrderPlus, sortOrderReduce, updateCategory } from '@/api/mall/category';

import { getToken } from '@/utils/auth';
import tableMixins from '@/mixins/table';

export default {
	name: 'Category',
	components: {},
	mixins: [tableMixins],
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 类目表格数据
			categoryList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				name: null,
				keywords: null,
				desc: null,
				pid: null,
				iconUrl: null,
				picUrl: null,
				level: null,
				sortOrder: null,
				categoryType: 1,
				type: null,
			},
			// 表单参数
			form: {},
			formLoading: false,
			// 表单校验
			rules: {
				name: [{ required: true, message: '类目名称不能为空', trigger: 'blur' }],
				level: [{ required: true, message: '请选择分类级别', trigger: 'blur' }],
				keywords: [{ required: true, message: '类目关键字', trigger: 'blur' }],
				pid: [{ required: true, message: '父类目ID不能为空', trigger: 'blur' }],
				iconUrl: [{ required: true, message: '请上传分类图片', trigger: 'blur' }],
			},
			catL1: {},
			maps: new Map(),
			cont: 0,
		};
	},
	computed: {
		headers() {
			return {
				Authorization: 'Bearer ' + getToken(),
			};
		},
	},
	created() {
		this.getList();
	},

	methods: {
		toSort(row, column, $index) {
			console.log(row);
			if (row.level == 'L1') {
				// this.cont++
				// let sort = this.cont ++
				return row.index;
			} else {
				return row.index;
			}
		},
		/** 查询类目列表 */
		had(scope) {
			console.log(scope);
			// return "11"
		},
		rowClassName({ row, rowIndex }) {
			row.xh = rowIndex + 1;
		},
		getList() {
			this.loading = true;
			listCategory(this.queryParams).then((response) => {
				this.categoryList = response.data.records;
				for (let i = 0; i < this.categoryList.length; i++) {
					this.categoryList[i].index = i + 1;
				}
				this.total = response.data.total;
				this.loading = false;
				this.setActionWidth();
			});

			listParent().then((response) => {
				this.catL1 = response.data;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				name: null,
				keywords: null,
				desc: null,
				pid: null,
				iconUrl: null,
				picUrl: null,
				level: null,
				sortOrder: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = '添加类目';
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			getCategory(id).then((response) => {
				this.open = true;
				this.title = '编辑类目';
				this.$nextTick(() => {
					this.form = response.data;
				});
			});
		},
		/** 提交按钮 */
		submitForm() {
			if (!this.form.iconUrl) {
				this.formLoading = false;
				return this.$message.error('请上传分类图标');
			}
			this.$refs['form'].validate((valid) => {
				if (valid) {
					this.formLoading = true;
					if (this.form.id != null) {
						updateCategory(this.form)
							.then(() => {
								this.msgSuccess('编辑成功');
								this.open = false;
								this.getList();
							})
							.finally(() => {
								this.formLoading = false;
							});
					} else {
						addCategory(this.form)
							.then(() => {
								this.msgSuccess('新增成功');
								this.open = false;
								this.getList();
							})
							.finally(() => {
								this.formLoading = false;
							});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let ids = [row.id || this.ids];
			this.$dialogRemove('确定删除该分类吗？').then((res) => {
				delCategory(ids)
					.then((response) => {
						this.$message({
							type: 'success',
							message: '删除成功!',
						});
						setTimeout(() => {
							this.getList();
							res.hide();
							res.loading(false);
						}, 100);
					})
					.catch(() => {
						res.loading(false);
					});
			});
		},

		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有类目数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportCategory(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
		onLevelChange: function (value) {
			if (value === 'L     1') {
				this.form.pid = 0;
			}
		},
		handleIconUrl(res, file) {
			console.log(res);
			this.form.iconUrl = res.url;
		},
		handlePicUrl(res, file) {
			this.form.picUrl = res.url;
		},
		load(tree, treeNode, resolve) {
			const pid = tree.id;
			this.maps.set(pid, { tree, treeNode, resolve });
			listChild(tree.id).then((response) => {
				for (let i = 0; i < response.data.length; i++) {
					response.data[i].index = i + 1;
				}
				resolve(response.data);
			});
		},
		handleStatusChange(row) {
			updateCategory(row)
				.then((response) => {
					this.$message.success(row.status ? '上架成功' : '下架成功');
				})
				.catch((err) => {
					row.status = !row.status;
				});
		},
		reSortOrderReduce(id, pid) {
			this.cont = 0;
			sortOrderReduce({ id: id, pid: pid })
				.then((response) => {
					this.getList();
					const { tree, treeNode, resolve } = this.maps.get(pid);
					this.$set(this.$refs.table.store.states.lazyTreeNodeMap, pid, []);
					this.load(tree, treeNode, resolve);
				})
				.catch((err) => {});
		},
		reSortOrderPlus(id, pid) {
			this.cont = 0;
			sortOrderPlus({ id: id, pid: pid })
				.then((response) => {
					this.getList();
					const { tree, treeNode, resolve } = this.maps.get(pid);
					this.$set(this.$refs.table.store.states.lazyTreeNodeMap, pid, []);
					this.load(tree, treeNode, resolve);
				})
				.catch((err) => {});
		},
	},
};
</script>
<style lang="scss" scoped>
.conncet {
	border-radius: 8px;
}

.pad-left {
	padding-left: 40px;
}

.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 130px;
	height: 130px;
	line-height: 130px;
	text-align: center;
}

.avatar {
	width: 130px;
	height: 130px;
	display: block;
}

.sortOrder {
	background: #ffffff;
	border-color: #cccccc;
	color: #86909c;
}

.sortOrder .el-icon-caret-top {
	color: #cccccc;
}

.sortOrder .el-icon-caret-bottom {
	color: #cccccc;
}
</style>
